var $BO = (function () {

    function _initList(domContainer) {
    	var obj = new BOList();
    	obj.container = domContainer;
    	obj.table = new BOList();
    	obj.modalAdd = obj.container.find('.modal-add');
    	obj.formAdd = obj.modalAdd.find('.form-add');
    	obj.modalEdit = obj.container.find('.modal-edit');
    	obj.formEdit = obj.modalEdit.find('.form-edit');
    	obj.formSearch = obj.container.find('.form-search');
    	obj.editors = new BOList();
        return obj;
    }

    function _initTreeTable(id, ajaxUrl, param, columns, treeId, treeField) {
        $('#' + id).bootstrapTable('destroy');
        var table = $('#' + id).bootstrapTable({
            url: ajaxUrl,
            method: "post",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            striped: true,//隔行变色
            cache: false,  //是否使用缓存
            sidePagination: 'server',
            pagination: false,
            treeCollapseAll: false,
            treeView: true,
            treeId: treeId,
            treeField: treeField,
            undefinedText: '--',
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            queryParams: function (params) {
                return param;
            },
            columns: columns
        });
        return table;
    }

    function _initTable(domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName) {
        var sidePagination = sidePagination || "server";
        pageSize = pageSize === undefined || pageSize == null ? 20 : pageSize;
        height = height === undefined ? $(window).height() - 200 : height;
        ajaxUrlEdit = ajaxUrlEdit === undefined ? ajaxUrl.replace('search', 'edit') : ajaxUrlEdit;
        primaryKeyName = primaryKeyName === undefined ? 'id' : primaryKeyName;
        var table = domTable.bootstrapTable('destroy').bootstrapTable({
            url: ajaxUrl,
            method: "post",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            striped: true,//隔行变色
            cache: false,  //是否使用缓存
            showColumns: true,// 列
            pagination: true, //分页
            paginationLoop: false,
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            showFooter:false,//显示列脚
            showPaginationSwitch: false,//是否显示数据条数选择框
            sortable: false, //是否启用排序
            singleSelect: true, // 是否单选框
            showRefresh: false,//是否显示刷新按钮
            
            stickyHeader: true,
            stickyHeaderOffsetLeft: '3em',
            stickyHeaderOffsetRight: '3em',
            theadClasses: 'thead-light',
            
            showExport: true, // 是否显示导出按钮
            exportDataType: 'all', // basic, all, selected
            exportTypes: ['excel'], // 导出文件格式
            exportOptions: {
                ignoreColumn: [0] //  // 导出数据去除第一列出现"on"
            },
            
            search: false, //显示搜索框
            showRefresh: false,
            sidePagination: sidePagination, //服务端处理分页
            clickToSelect: true,
            queryParamsType: '',
            pageNumber : 1,
            pageSize: pageSize,
            pageList: [5, 20, 50, 1000],
            queryParams: function queryParams(params) {//自定义参数，这里的参数是传给后台的，我这是是分页用的
                param.size = params.pageSize;
                param.page = (params.pageNumber - 1) * params.pageSize;
                return param;
            },
            columns: columns,
            height: height,
            onEditableSave: function (field, row, oldValue, $el) {
            	var dataJO = new Object();
            	dataJO[field] = row[field];
            	dataJO[primaryKeyName] = row[primaryKeyName];
                $.ajax({
                    type: "post",
                    url: ajaxUrlEdit,
                    data: dataJO,
                    dataType: 'JSON',
                    success: function (data) {
                        if (data.code == 0) {
                            alert('提交数据成功');
                        } else {
                        	alert(data.msg);
                        }
                    },
                    error: function () {
                        alert('编辑失败');
                    },
                    complete: function () {

                    }

                })
            }
        });
        return table;
    }

    function _initTableFixHeader(domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName) {
        var table = domTable.bootstrapTable('destroy').bootstrapTable({
            columns: columns
        });
        return table;
    }

    function _initTree(id, ajaxUrl, param) {
        var setting = {
            async: {
                enable: true,
                url: ajaxUrl,
                otherParam: param
            },
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onClick: function (e, treeId, treeNode, clickFlag) {
                    treeObj.checkNode(treeNode, !treeNode.checked, true);
                }
            }
        };
        $.fn.zTree.init($("#" + id), setting);
        var treeObj = $.fn.zTree.getZTreeObj(id);
        return treeObj;
    }

    function _initTreeRadio(id, ajaxUrl, param) {
        var setting = {
            async: {
                enable: true,
                url: ajaxUrl,
                otherParam: param
            },
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            view: {
                //是否显示连接线
                showLine: true,
                //是否显示节点图标（默认为true）
                showIcon: false
            },
            callback: {
                onClick: function (e, treeId, treeNode, clickFlag) {
                    treeObj.checkNode(treeNode, !treeNode.checked, true);
                }
            }
        };
        $.fn.zTree.init($("#" + id), setting);
        var treeObj = $.fn.zTree.getZTreeObj(id);
        return treeObj;
    }

    function _initSummernote(id) {
        $('#' + id).summernote({
            height: 200,
            // minHeight: 200,
            // maxHeight: 500,
            lang: 'zh-CN',
            focus: true,
            onImageUpload: function (files) {
            	
                $.ajax({
                    type: "POST",
                    url: "/api/outer/upload/getQiniuToken",
                    success: function (data) {
                        if (data.code != 0) {
                            alert(data.msg);
                            return;
                        }
                        var token = data.data.authtoken;
                        var domain = data.data.domain;
                        var config = {
                            useCdnDomain: true,
                            disableStatisticsReport: false,
                            retryCount: 6
                        };
                        var putExtra = {
                            fname: "",
                            params: {},
                            mimeType: ["image/png", "image/jpeg", "image/gif"]
                        };

                        for (var i = 0; i < files.length; i++) {
                            var file = files[i];
                            if (file) {
                            	var fileName = file.name;
                            	var index = fileName.lastIndexOf('.');
                            	var fileNameSuffix = fileName.substr(index);
                                var fileHalfName = getAppUploadFileName(fileNameSuffix);

                                var error = function (err) {
                                };

                                var next = function (response) {
                                    // var chunks = response.chunks || [];
                                    // var total = response.total;
                                };
                                
                                var complete = function (res) {
                                	console.log(res);
                                    if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
                                        var url = domain + '/' + res.key;
                                        console.log(url);
                                        $('#' + id).summernote('insertImage', url, 'img');
                                    }
                                };
                                
                                var subObject = {
                                    next: next,
                                    error: error,
                                    complete: complete
                                };
                                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                                var observable = qiniu.upload(file, fileHalfName, token, putExtra, config);
                                var subscription = observable.subscribe(subObject);
                                // subscription.unsubscribe();
                            }
                        }
                    }
                });
            }
        });
    }

    /**
     * 初始化 kindeditor 区域
     */
    function _initKindEditor(id) {
    	var config = {
    		"width": "100%",
    		"height": 450,
    		"resizeType": 0,
    		"autoHeightMode": false,
    		"items": [
    			'source', '|',
    			'undo', 'redo', '|',
    			'preview', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|',
    			'justifyleft', 'justifycenter', 'justifyright',
    			'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'clearhtml', 'quickformat', 'selectall', '/',
    			'formatblock', 'fontname', 'fontsize', '|',
    			'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|',
    			'image', 'multiimage', 'insertfile', 'link', 'unlink'
    		],
    		"allowImageRemote": false,
    		"uploadJson": "/api/outer/upload/uploadfileForEditor",
    		"filePostName": "fileStream",
    		"formatUploadUrl": false
    	};
    	return KindEditor.create('#' + id, config);
    }

    function _initFileInput(domFile, imgUrl) {
    	var domInput = domFile.parent().parent().parent().find('.bo-input-4');

    	domFile.fileinput('destroy');
    	domFile.fileinput({
    	    theme: 'fas',
    	    uploadUrl: 'http://up.qiniu.com',
    	    allowedFileExtensions : ['jpg', 'png','gif'], // 接收的文件后缀
    	    maxFileCount: 3,
    	    enctype: 'multipart/form-data',
    	    uploadAsync:false, // false 同步上传，后台用数组接收，true 异步上传，每次上传一个file,会调用多次接口
    	    browseLabel: '选择文件',
    	    showRemove:false, // 显示移除按钮
    	    showCancel:false, // 显示取消按钮
    	    showCaption:false, // 显示文件文本框
    	    showUpload:false, // 显示上传按钮
    	    showPreview:true, // 显示预览图
    	    showClose:false, // 显示右上角关闭图标
    	    initialPreviewAsData: true, //实现初始化预览
    	    fileActionSettings: {                               // 在预览窗口中为新选择的文件缩略图设置文件操作的对象配置
                showRemove: false,                                   // 显示删除按钮
                showUpload: false,                                   // 显示上传按钮
                showDownload: false,                            // 显示下载按钮
                showZoom: false,                                    // 显示预览按钮
                showDrag: false                                        // 显示拖拽
            },
            initialPreview: [imgUrl]
    	}).on('filebatchselected', function (event, files) {
    		var fileJO = files[Object.keys(files)[0]];
    		var fileName = fileJO.name;
        	var filenameSuffix = fileName.substr(fileName.lastIndexOf('.'));
    		var key = getAppUploadFileName(filenameSuffix);
    		console.log(key);
    		var file = files[Object.keys(files)[0]].file;
    		var domain = '';
            var error = function (err) {
            	alert('上传失败！');
                console.log(err);
            };

            var next = function (response) {
            };
            
            var complete = function (res) {
                if (res.key && res.key.match(/\.(jpg|jpeg|png|gif|xls|xlsx)$/)) {
                    var url = domain + '/' + res.key;
                    domInput.val(url);
                }
            };
            
            var putExtra = {
                    fname: "",
                    params: {},
//                    mimeType: ["image/png", "image/jpeg", "image/gif"]
                    mimeType: null
                };
            var config = {
                    useCdnDomain: true,
                    disableStatisticsReport: false,
                    retryCount: 6
                };

            var subObject = {
                next: next,
                error: error,
                complete: complete
            };
    		
    		$.ajax({
    			type: "POST",
    			url: "/api/outer/upload/getQiniuToken",
    			async: false,
    			data: {},
    			success: function (data) {
    				if (data.code == 0) {
    					var token = data.data.authtoken;
    					domain = data.data.domain;
    					var observable = qiniu.upload(file, key, token, putExtra, config);
    			        var subscription = observable.subscribe(subObject);
    				} else {
    					alert(data.msg);
    				}
    			}
    		});

            
    		//$(this).fileinput("upload");
    	}).on("fileuploaded", function(event, data) {
    		console.log(data.response);
    	});
    }

    function _qiniuUpload(file_id, val_id, img_id) {
        $.ajax({
            type: "POST",
            url: "/api/outer/upload/getQiniuToken",
            success: function (res) {
                if (res.code != 0) {
                    alert(res.msg);
                    return;
                }
                var token = res.data.authtoken;
                var domain = res.data.domain;
                var config = {
                    useCdnDomain: true,
                    disableStatisticsReport: false,
                    retryCount: 6
                };
                var putExtra = {
                    fname: "",
                    params: {},
//                    mimeType: ["image/png", "image/jpeg", "image/gif"]
                    mimeType: null
                };
                uploadWithSDK(file_id, val_id,img_id, token, putExtra, config, domain);
            }
        });
    }

    function _qiniuUploadByDom(fileDom, valDom, imgDom) {
        $.ajax({
            type: "POST",
            url: "/api/outer/upload/getQiniuToken",
            success: function (res) {
                if (res.code != 0) {
                    alert(res.msg);
                    return;
                }
                var token = res.data.authtoken;
                var domain = res.data.domain;
                var config = {
                    useCdnDomain: true,
                    disableStatisticsReport: false,
                    retryCount: 6
                };
                var putExtra = {
                    fname: "",
                    params: {},
//                    mimeType: ["image/png", "image/jpeg", "image/gif"]
                    mimeType: null
                };
                uploadWithSDKByDom(fileDom, valDom, imgDom, token, putExtra, config, domain);
            }
        });
    }

    return {
        initTable: function (domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName) {
            return _initTable(domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName);
        },
        initTableFixHeader: function (domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName) {
            return _initTableFixHeader(domTable, ajaxUrl, param, columns, pageSize, height, ajaxUrlEdit, primaryKeyName);
        },
        initTree: function (id, ajaxUrl, param) {
            return _initTree(id, ajaxUrl, param);
        },
        initTreeRadio: function (id, ajaxUrl, param) {
            return _initTreeRadio(id, ajaxUrl, param);
        },
        initTreeTable: function (id, ajaxUrl, param, columns, treeId, treeField) {
            return _initTreeTable(id, ajaxUrl, param, columns, treeId, treeField);
        },
        initSummernote: function (id) {
            return _initSummernote(id);
        },
        initKindEditor : function (id) {
        	return _initKindEditor(id);
        },
        qiniuUpload: function (file_id, val_id,img_id) {
            return _qiniuUpload(file_id, val_id, img_id);
        },
        qiniuUploadByDom: function (fileDom, valDom, imgDom) {
            return _qiniuUploadByDom(fileDom, valDom, imgDom);
        },
        initList: function (domContainer) {
            return _initList(domContainer);
        },
        initFileInput: function (domFile, imgUrl) {
            return _initFileInput(domFile, imgUrl);
        }
    }
})($);